package com.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.PostConstruct;

/**
 * @Description TODO
 * @Author JFeng
 * @Date 2024/5/26
 */

@Configuration
public class GatewayConfig {

    @PostConstruct
    public void init() {
        BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
            if (throwable instanceof FlowException) {
                return ServerResponse.status(429) // Too Many Requests
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue("{\"code\": 429, \"message\": \"流控规则限制\"}"));
            } else if (throwable instanceof DegradeException) {
                return ServerResponse.status(503) // Service Unavailable
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue("{\"code\": 503, \"message\": \"服务降级处理\"}"));
            } else if (throwable instanceof BlockException) {
                return ServerResponse.status(429) // Too Many Requests
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue("{\"code\": 429, \"message\": \"BlockException 限制\"}"));
            } else {
                return ServerResponse.status(500) // Internal Server Error
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue("{\"code\": 500, \"message\": \"未知异常\"}"));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}
